<template>
  <div>
    <en-table-layout toolbar pagination :loading="loading" :tableData="tableData">
      <div slot="toolbar" class="inner-toolbar">
        <div>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-download"
            @click="handleExportOrderItems"
          >导出订单明细</el-button>
          <el-button type="primary" @click="openDialog()">打印小票</el-button>
          <el-button type="text">
            <a href="https://egale-shop.oss-cn-hangzhou.aliyuncs.com/XP58mm%20Driver.zip">打印驱动下载</a>
          </el-button>
        </div>
        <div class="top-search">
          <div style="margin-right:10px">
            <span style="font-size: 14px;">订单状态：</span>
            <el-select
              v-model="params.order_status"
              placeholder="请选择订单状态"
              @change="changeOrderStatus"
              clearable>
              <el-option
                v-for="item in orderStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <en-table-search
            @search="searchEvent"
            @advancedSearch="advancedSearchEvent"
            advanced
            advancedWidth="480"
            placeholder="请输入订单编号或者商品名称">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="100px">
                <el-form-item label="订单编号">
                  <el-input v-model="advancedForm.order_sn" clearable placeholder="订单编号"></el-input>
                </el-form-item>
                <el-form-item label="商品名称">
                  <el-input v-model="advancedForm.goods_name" clearable placeholder="商品名称"></el-input>
                </el-form-item>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="收货人姓名" prop="ship_name">
                      <el-input v-model="advancedForm.ship_name" placeholder="收货人姓名"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="收货人电话" prop="ship_mobile">
                      <el-input v-model="advancedForm.ship_mobile" placeholder="收货人电话"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="买家">
                  <el-input v-model="advancedForm.buyer_name" clearable placeholder="买家"></el-input>
                </el-form-item>
                <el-form-item label="下单时间">
                  <el-date-picker
                    v-model="advancedForm.order_time_range"
                    type="datetimerange"
                    align="center"
                    :editable="false"
                    unlink-panels
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :default-time="['00:00:00', '23:59:59']"
                  ></el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>
    </en-table-layout>
    <div class="my-table-out" :style="{maxHeight: tableMaxHeight + 'px'}">
      <table class="my-table">
        <thead>
          <tr class="bg-order">
            <th class="shoplist-header">
              <span><el-checkbox :indeterminate="isIndeterminate" @change="handleAll()"></el-checkbox>全选</span>
              <span style="width: 100%;">商品名称</span>
              <span>单价/数量</span>
            </th>
            <th>买家</th>
            <!--<th>下单时间</th>-->
            <th>订单状态</th>
            <!--<th>来源</th>-->
            <th>实付金额</th>
          </tr>
        </thead>
        <tbody v-for="(item,index) in tableData" :key="index">
          <tr style="width: 100%;height: 10px;"></tr>
          <tr class="bg-order">
            <td class="shoplist-content-out" colspan="3">
              <el-checkbox @change="handleCheck(item)" v-model="item.checked"></el-checkbox>
              <!-- @selection-change="handleSelectionChange" -->
              订单编号：{{item.sn}}
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              下单时间: {{ item.create_time | unixToDate }}
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              来源: {{ item.client_type }}
              <svg-icon
                v-if="item.client_type === 'PC'"
                iconClass="pc"
                style="width: 15px;height: 15px;"
              />
              <svg-icon
                v-if="item.client_type === 'WAP' || item.client_type === 'APP'"
                iconClass="mobile"
                style="width: 15px;height: 15px;"
              />
            </td>
            <td>
              <el-button type="text" @click="handleOperateOrder(item)">查看详情</el-button>
            </td>
          </tr>
          <tr>
            <!--商品-->
            <td>
              <p v-for="(shop,index) in item.sku_list" class="shoplist-content" :key="index">
                <span class="goods-info">
                  <img :src="shop.goods_image" alt class="goods-image" />
                  <a
                    :href="`${MixinBuyerDomain}/goods/${shop.goods_id}`"
                    target="_blank"
                    style="color: #00a2d4;"
                  >{{ shop.name }}</a>
                </span>
                <span>
                  <a
                    class="trade-record"
                    :href="`${MixinBuyerDomain}/goods/snapshot?id=${shop.snapshot_id}&sku_id=${shop.sku_id}&orderData=${item.order_amount}`"
                    target="_blank"
                  >
                    <el-button type="text">交易快照</el-button>
                  </a>
                  <span>{{shop.original_price | unitPrice('￥')}}</span> ×
                  <span>{{ shop.num }}</span>
                </span>
              </p>
            </td>
            <!--买家-->
            <td>{{ item.member_nick_name }}</td>
            <!--订单状态-->
            <td>{{ item.order_status_text }}</td>
            <!--实付金额-->
            <td>
              <div class="order-money">
                <!--订单总金额-->
                <span class="order-amount">{{ item.order_amount | unitPrice('￥')}}</span>
                <!--运费/邮费-->
                <span>运费({{ item.shipping_amount | unitPrice('￥') }})</span>
                <!--支付方式-->
                <span>{{ item.payment_name }}</span>
              </div>
            </td>
          </tr>
        </tbody>
        <div v-if="tableData.length === 0 " class="empty-block">暂无数据</div>
      </table>
    </div>
    <el-pagination
      v-if="pageData"
      slot="pagination"
      @size-change="handlePageSizeChange"
      @current-change="handlePageCurrentChange"
      :current-page="pageData.page_no"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageData.page_size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageData.data_total">
    </el-pagination>
      <el-dialog
      :title="'已选中'+ checkbox.length +'个订单'"
      :visible.sync="DialogVisible"
      width="300px"
      :append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      >
      <div id="mycontent" style="display:none;">
        <div id="advancePrint" style="padding:10px;box-sizing:border-box;">
          <div v-for="(item,index) in printOrder" :key="index">
            <div style="text-align: left;font-size:14px; white-space:nowrap;font-weight: bold;padding-top:20px">订单号：{{item.sn}}</div>
            <div style="text-align: left;white-space:nowrap;font-size:14px;font-weight: bold">下单时间：{{item.create_time | unixToDate("yyyy-MM-dd hh:mm") }}</div>
            <div style="text-align: left;margin-bottom:10px;font-size:14px;font-weight: bold">配送方式：{{item.shipping_type === 'SELF' ? "站点自提" : "快递到家"}}</div>
            <!-- <div style="margin-bottom:20px;">{{item.create_time | unixToDate("yyyy-MM-dd hh:mm:ss") }}</div> -->
            <div style="width:100%; border-top:dashed 1px black; border-bottom:dashed 1px black; height:5px;
            margin-bottom:20px; line-height:5px; text-align: center;">
              <span style="font-weight:bold; font-size: 20px; background: #fff; padding-left:10px; padding-right:10px; z-index:999;">#{{item.order_seq === null ? '' : item.order_seq}}</span>
            </div>
            <div style="text-align: center;"><span>{{item.seller_name}}</span></div>
            <div style="text-align: center; font-weight: bold; font-size:20px; margin-top:10px;">{{item.cancel_reason}}</div>
            <!-- 二维码 -->
              <div style="text-align:center;">
                  <barcode :value="item.sn" :width="1.5" :font-size="15"  :height="40" :displayValue="false">
                    条形码显示失败
                  </barcode>
              </div>
            <div style="width:100%;display:flex;border-top:1px dashed black;border-bottom:1px dashed black;" >
              <div style="flex:2;padding:6px 0;font-weight:800;">商品名称</div>
              <div style="flex:1;padding:6px 0;font-weight:800;">数量</div>
              <div style="flex:1;padding:6px 0;font-weight:800;">单价</div>
            </div>
            <div v-for="(count,index) in item.order_sku_list" :key="index">
              <div style="display:flex;align-items:flex-start">
                <span style="flex:2;padding:6px;font-size:14px;">{{count.name}}</span>
                <span style="flex:1;font-weight:600;padding:6px;font-size:14px;">{{"×"+count.num}}</span>
                <span style="flex:1;padding:6px;font-size:14px;">{{count.purchase_price}}</span>
              </div>
            </div>
            <div style="width:100%; border-bottom:dashed 1px black; height:5px;
            margin-bottom:20px; margin-top:6px; text-align: center;"></div>
            <div style="margin-bottom:10px;">配送费：{{item.shipping_price}}</div>
            <div style="font-weight:bold; font-size: 20px;">合计：{{item.order_price}}</div>
            <div style="width:100%; border-bottom:dashed 1px black; height:5px;
            margin-bottom:20px; margin-top:20px; line-height:5px; text-align: center;"></div>
            <div v-if="item.leader !== null" style="margin-bottom:10px; font-weight: bold">自提站点：{{item.leader.site_name}}</div>
            <div v-if="item.leader !== null" style="margin-bottom:10px; font-weight: bold">站长姓名：{{item.leader.leader_name}}</div>
            <div v-if="item.leader !== null" style="margin-bottom:10px; font-weight: bold">站长电话：{{item.leader.leader_mobile}}</div>
            <div v-if="item.leader !== null" style="margin-bottom:10px; font-weight: bold;">站点地址：{{item.leader.city}} {{item.leader.county}} {{item.leader.address}}</div>
            <div style="width:100%; border-bottom:dashed 1px black; height:5px;
            margin-bottom:20px; margin-top:20px; line-height:5px; text-align: center;"></div>
            <div style="font-weight:bold; font-size: 16px;">
              <div>
              {{item.ship_province}}{{item.ship_city}}{{item.ship_county}}{{item.ship_addr}}
              </div>
              <div>
                {{item.ship_mobile}}
              </div>
              <div>
                {{item.ship_name}}
              </div>
            </div>
            <div style="width:100%; border-bottom:dashed 1px black; height:5px;
            margin-bottom:30px; margin-top:10px; line-height:5px; text-align: center;"></div>
            <div style="text-align: left;font-size:12px; white-space:nowrap;">订单号：{{item.sn}}</div>
            <div style="text-align: left;white-space:nowrap;font-size:12px;margin-top:6px">下单时间：{{item.create_time | unixToDate("yyyy-MM-dd hh:mm") }}</div>
            <div style="width:100%; border-top:dashed 1px black; height:5px;
              padding-bottom:70px; line-height:5px; text-align: center; margin-top:20px;">
              <span style="font-weight:bold; font-size: 20px; background: #fff; padding-left:10px; padding-right:10px;  z-index: 9999;"> #{{item.order_seq === null ? '' : item.order_seq}}完</span>
            </div>
          </div>
        </div>
      </div>
      <div class="footer">
        <div class="infooter">
          <el-button type="primary" @click="printPdf()" :loading="btn_loading">{{printText}}</el-button>
          <el-button type="primary" @click="previewOrder()">预览</el-button>
          <el-button @click="DialogVisible=false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="修改收获地址"
      :visible.sync="addressDialog"
      width="400px">
      <el-form>
        <el-form-item>

        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import * as API_order from "@/api/order";
import { CategoryPicker } from "@/components";
import { getLodop } from "../../utils/LodopFuncs";
import VueBarcode from 'vue-barcode';
export default {
  name: "orderList",
  components: {
    [CategoryPicker.name]: CategoryPicker,
    'barcode': VueBarcode
  },
  data() {
    return {
      /** 列表loading状态 */
      loading: false,
      btn_loading: false,
      DialogVisible: false,
      addressDialog: false,
      // checked: false,
      /** 列表参数 */
      params: {
        page_no: 1,
        page_size: 50,
        ...this.$route.query
      },
      // 订单打印数据
      printOrder: [],
      printText: "打印小票",
      /** 列表数据 */
      tableData: [],

      /** 列表分页数据 */
      pageData: [],

      /** 高级搜索数据 */
      advancedForm: {},

      /** 订单状态 列表*/
      orderStatusList: [
        { value: "ALL", label: "全部" },
        { value: "WAIT_PAY", label: "待付款" },
        { value: "WAIT_SHIP", label: "待发货" },
        { value: "WAIT_ROG", label: "待收货" },
        { value: "ROG", label: "已收货" },
        { value: 'WAIT_COMMENT', label: '待评价' },
        { value: "COMPLETE", label: "已完成" },
        { value: "CANCELLED", label: "已取消" }
      ],
      checkbox: [],
      isIndeterminate: false,
      /** 表格最大高度 */
      tableMaxHeight: document.body.clientHeight - 54 - 34 - 50 - 15
    };
  },
  mounted() {
    this.GET_OrderList();
  },
  activated() {
    delete this.params.market_enable;
    this.params = {
      ...this.params,
      ...this.$route.query
    };
    this.GET_OrderList();
    window.onresize = this.countTableHeight;
  },
  beforeRouteUpdate(to, from, next) {
    delete this.params.market_enable;
    this.params = {
      ...this.params,
      ...this.$route.query
    };
    this.GET_OrderList();
    next();
  },
  methods: {
    /**
     * @date 2020/08/21
     * @author kjh
     * @description {打印订单中的预览显示}
     */
    redis() {
      document.getElementById("mycontent").style.display = "block";
    },
    /**
     * @date 2020/08/21
     * @author kjh
     * @description {选中单个订单触发的事件}
     */
    handleCheck(item) {
      if (item.checked === true) {
        this.checkbox.push(item.sn);
      } else {
        this.checkbox.forEach((_sn, i) => {
          if (_sn === item.sn) {
            this.checkbox.splice(i, 1); // 从下标 i 开始, 删除 1 个元素
          }
        });
      }
      if (this.checkbox.length === this.tableData.length) {
        this.isIndeterminate = false;
      } else {
        this.isIndeterminate = true;
      }
    },
    /**
     * @date 2020/08/21
     * @author kjh
     * @description {全选所有订单}
     */
    handleAll() {
      if (this.checkbox.length !== this.tableData.length) {
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].checked === false) {
            this.$set(this.tableData[i], "checked", true);
            this.checkbox.push(this.tableData[i].sn);
          }
        }
      } else {
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].checked === true) {
            this.$set(this.tableData[i], "checked", false);
            this.checkbox.pop(this.tableData[i].sn);
          }
        }
      }
      if (this.checkbox.length === this.tableData.length) {
        this.isIndeterminate = !this.isIndeterminate;
      } else {
        this.isIndeterminate = true;
      }
      this.$forceUpdate();
    },
    previewOrder() {
      document.getElementById('mycontent').style.display="block";
    },
    /**
     * @date 2020/08/21
     * @author kjh
     * @description {打印订单}
     */
    printPdf() {
      this.btn_loading = true;
      setTimeout(() => {
        let LODOP = getLodop();
        LODOP.PRINT_INIT('面单打印');
        LODOP.SET_PRINT_STYLE('FontSize', 15);
        LODOP.SET_PRINT_PAGESIZE(3, 1200, 80, '');
        LODOP.SET_PRINT_STYLE('Bold', 1);
        LODOP.ADD_PRINT_HTM(0, 0, '100', '70%', document.getElementById('advancePrint').innerHTML);
        // LODOP.PREVIEW();
        LODOP.PRINT();
        this.DialogVisible = false;
        this.btn_loading = false;
      }, 1000);
    },
    /** 计算高度 */
    countTableHeight() {
      this.tableHeight = document.body.clientHeight - 54 - 35 - 50;
    },

    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.checkbox = [];
      this.GET_OrderList();
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.checkbox = [];
      this.GET_OrderList();
    },

    /** 订单状态改变 */
    changeOrderStatus(data) {
      delete this.params.keywords;
      delete this.params.order_status;
      if (data) {
        this.params = {
          ...this.params,
          order_status: data
        };
        this.params.page_no = 1;
        this.params.page_size = 10;
      }
      Object.keys(this.advancedForm).forEach(key => delete this.params[key]);
      this.GET_OrderList();
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keywords: data
      };
      delete this.params.order_status;
      Object.keys(this.advancedForm).forEach(key => delete this.params[key]);
      this.GET_OrderList();
    },

    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      };
      delete this.params.start_time;
      delete this.params.end_time;
      if (this.advancedForm.order_time_range) {
        this.params.start_time =
          this.advancedForm.order_time_range[0].getTime() / 1000;
        this.params.end_time =
          this.advancedForm.order_time_range[1].getTime() / 1000;
      }
      delete this.params.keywords;
      delete this.params.order_time_range;
      this.GET_OrderList();
    },

    /** 查看、操作订单 */
    handleOperateOrder(item) {
      let num = '1';
      this.$router.push({ path: `/order/detail/${item.sn}`, query: { ident: num }});
    },
    GET_OrderList() {
      this.loading = true;
      API_order.getOrderList(this.params).then(response => {
        this.loading = false;
        this.tableData = response.data;
        for (let i = 0; i < this.tableData.length; i++) {
          this.tableData[i].checked = false;
        }
        this.pageData = {
          page_no: response.page_no,
          page_size: response.page_size,
          data_total: response.data_total
        };
      });
    },

    /** 导出订单 */
    handleExportOrderItems() {
      if (this.params.start_time && this.params.end_time) {
        this.params.start_time = parseInt(this.params.start_time / 1000);
        this.params.end_time = parseInt(this.params.end_time / 1000);
      }
      API_order.exportOrderItems(this.params).then((response) => {
        // 处理返回的文件流
        let blob = new Blob([response], {
          type: "application/vnd.ms-excel;charset=utf-8"
        });
        let date =
          new Date().getFullYear() +
          "" +
          (new Date().getMonth() + 1) +
          "" +
          new Date().getDate();
        const fileName = date + name + "订单明细导出.xlsx";
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
      }).catch((err) => {
        this.$message.warning(err);
      });
    },

    openDialog() {
      if (!this.checkbox.length) {
        this.$message.warning(`请选择订单！`);
        return;
      }
      this.printText = "加载数据中";
      this.btn_loading = true;
      this.DialogVisible = true;
      let _ids = this.checkbox.toString();
      API_order.getByOrderSnList(_ids)
        .then(response => {
          this.btn_loading = false;
          this.printText = "打印小票";
          this.printOrder = response;
        })
        .catch(() => {
          this.btn_loading = false;
        });
    },
    // 修改收获地址
    uploadAddress() {
      if (this.checkbox.length === 0) {
        this.$message({
          type: 'error',
          message: '您还没有选择数据!!!'
        })
      } else if (this.checkbox.length > 1) {
        this.$message({
          type: 'error',
          message: '只能选择一条数据哦!!!'
        })
      } else {
        this.addressDialog = true;
      }
    }
  }
};
</script>

<style type="text/scss" lang="scss" scoped>
/deep/ div.toolbar {
  height: 70px;
  padding: 20px 0;
}
/* 工具条*/
.inner-toolbar {
  display: flex;
  width: 100%;
  justify-content: space-between;
  padding: 0 20px;
}

.el-input__inner {
  width: 100%;
}

/*暂无数据时的样式*/
/deep/ .el-table__empty-block {
  display: none;
}

.empty-block {
  position: relative;
  min-height: 60px;
  line-height: 60px;
  text-align: center;
  width: 190%;
  height: 100%;
  font-size: 14px;
  color: #606266;
}

/*表格信息*/
.my-table-out {
  white-space: nowrap;
  overflow-y: scroll;
  text-overflow: ellipsis;
  width: 100%;
  max-height: 800px;
}
.my-table {
  width: 100%;
  margin-bottom: 40px;
  background: #fff;
  border-collapse: collapse;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
    Microsoft YaHei, Arial, sans-serif;
  font-size: 14px;
  font-weight: 700px;
  .bg-order {
    background: #fafafa;
  }
  thead {
    th {
      padding: 10px 0;
      border: 1px solid #ebeef5;
      border-collapse: collapse;
      color: #909399;
    }
    th.shoplist-header {
      padding: 10px 20px;
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-between;
      align-items: center;
    }
  }
  tbody {
    margin-top: 10px;
    td {
      border: 1px solid #ebeef5;
      border-collapse: collapse;
      text-align: center;
      padding: 0;
    }
    td:first-child {
      text-align: left;
    }
    td:not(:first-child) {
      padding: 3px;
    }
    td.shoplist-content-out {
      padding-left: 20px;
    }

    /*商品信息*/
    p.shoplist-content:not(:last-child) {
      border-bottom: 1px solid #ebeef5;
      border-collapse: collapse;
    }
    p.shoplist-content {
      margin: 0;
      padding: 0 20px;
      box-sizing: padding-box;
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-between;
      align-items: center;
      .goods-info {
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: flex-start;
        align-items: center;
        padding: 10px 0;
        img {
          display: block;
          margin-right: 10px;
        }
        a {
          display: block;
          color: #409eff;
        }
      }
    }
    div.order-money {
      display: flex;
      flex-direction: column;
      flex-wrap: nowrap;
      justify-content: center;
      align-items: center;
      span {
        display: inline-block;
        padding: 5px;
      }
      span.order-amount {
        color: red;
      }
    }
  }
  /* 商品图片 */
  .goods-image {
    width: 50px;
    height: 50px;
  }
  /** 交易快照 */
  .trade-record {
    display: inline-block;
    margin-right: 50px;
  }
}

/*分页信息*/
section > div {
  position: relative;
}
.el-pagination {
  text-align: right;
  width: 100%;
  background: #ffffff;
  height: 40px;
  position: absolute;
  bottom: 0;
  right: 0;
  border-top: 1px solid #e5e5e5;
  padding: 5px 20px;
}
.order-status {
  margin-right: 500px;
  display: inline;
}
.footer {
  display: flex;
  justify-content: center;
}
.top-search{
  display: flex;
  flex-flow: row nowrap;
    .conditions {
      margin-right: 10px;
      font-size: 12px;
    }
}
</style>

